package com.citywithincity.db.sync;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.citywithincity.db.Db;
import com.citywithincity.db.Record;
import com.citywithincity.db.interfaces.Ar;
import com.citywithincity.db.interfaces.IValueConvert;
import com.citywithincity.interfaces.IDestroyable;

class SyncFieldsContainer implements IDestroyable {
	
	private String[] srcFields;
	private String[] targetFields;
	private IValueConvert[] converts;
	private int targetDb;
	private SyncDataHandler handler;
	private SyncAfter after;
	
	public SyncFieldsContainer(String[] srcFields,
			String[] targetFields,
			IValueConvert[] converts,
			int targetDb,
			SyncDataHandler handler,
			SyncAfter after){
		
		this.after = after;
		this.targetFields = targetFields;
		this.converts = converts;
		this.targetDb = targetDb;
		this.handler = handler;
		
		/**
		 * 检查是否有as
		 */
		this.srcFields = new String[srcFields.length];
		int index = 0;
		for (String field : srcFields) {
			
			if(field.contains(" AS ")){
				this.srcFields[index]=field.substring(field.indexOf(" AS ")+" AS ".length());
			}else{
				this.srcFields[index] = field;
			}
			++index;
		}
		
	}
	
	@Override
	public void destroy() {
		this.srcFields = null;
		this.targetFields = null;
		this.converts = null;
		this.handler = null;
	}
	
	private static final Log logger = LogFactory.getLog(SyncFieldsContainer.class);
	
	public void syncList(SyncInsertMethod insert,List<Record> list){
		final String[] srcFields = this.srcFields;
		final String[] targetFields = this.targetFields;
		final IValueConvert[] converts = this.converts;
		
		Ar ar = Db.ar(targetDb);
		
		for (Record record : list) {
			for (int i = 0 ,c = srcFields.length; i < c; i++) {
				Object value = record.get(srcFields[i]);
				IValueConvert convert = converts[i];
				if(convert!=null && value!=null){
					value = convert.convert(value);
				}
				ar.set(targetFields[i],value);
			}
			
			if(handler!=null){
				handler.handleData(record, ar);
			}
			if(after!=null){
				Record r = new Record();
				ar.syncTo(r);
				logger.info(r);
				if(insert.insert(ar)>0){
					after.afterInsert(r);
				}
			}else{
				insert.insert(ar);
			}
			
		}
		if(after!=null){
			after.handle();
		}
	}


	
}
